import * as fs from 'fs';
import { resolve } from 'path';

// 判断文件或者文件夹是否存在
type dir = '' | 'file' | 'dir'
export function isExists(url: string): dir {
    if (!url) return ''
    try {
        const file = fs.statSync(url)
        return file.isDirectory() ? 'dir' : 'file'
    } catch (err) {
        return ''
    }
}

/**
 * 递归清空文件夹内容
 * @param {string} path
 */
export const delDir = (path: string) => {
    let files = [];
    if (fs.existsSync(path)) {
        files = fs.readdirSync(path);
        files.forEach((file, index) => {
            const curPath = resolve(path, file);
            if (fs.statSync(curPath).isDirectory()) {
                delDir(curPath); //递归删除文件夹
            } else {
                fs.unlinkSync(curPath); //删除文件
            }
        });
        fs.rmdirSync(path);
    }
};
/* 清除unicloud文件夹下除package.json所有文件 */
export const clearUniDir = () => {
    const path = resolve(process.cwd(),process.env.UNICLOUDURL as string)
    if (fs.existsSync(path)) {
        const files = fs.readdirSync(path);
        files.forEach((file, index) => {
            const curPath = resolve(path, file);
            if (fs.statSync(curPath).isDirectory()) {
                delDir(curPath); //递归删除文件夹
            } else {
                if (file !== "package.json") {
                    fs.unlinkSync(curPath); //删除文件
                }
            }
        })
    }
}

/**
 * 复制文件夹到目标文件夹
 * @param {string} src 源目录
 * @param {string} dest 目标目录
 * @param {function} callback 回调
 */
export const copyDir = (src: string, dest: string, callback?: Function) => {
    const copy = (copySrc: string, copyDest: string) => {
        fs.readdir(copySrc, (err, list) => {
            if (err) {
                callback && callback(err);
                return;
            }
            list.forEach((item) => {
                const ss = resolve(copySrc, item);
                fs.stat(ss, (err, stat) => {
                    if (err) {
                        callback && callback(err);
                    } else {
                        const curSrc = resolve(copySrc, item);
                        const curDest = resolve(copyDest, item);

                        if (stat.isFile()) {
                            // 文件，直接复制
                            fs.createReadStream(curSrc).pipe(fs.createWriteStream(curDest));
                        } else if (stat.isDirectory()) {
                            // 目录，进行递归
                            fs.mkdirSync(curDest, { recursive: true });
                            copy(curSrc, curDest);
                        }
                    }
                });
            });
        });
    };

    fs.access(dest, (err) => {
        if (err) {
            // 若目标目录不存在，则创建
            fs.mkdirSync(dest, { recursive: true });
        }
        copy(src, dest);
    });
};